package com.unisedu.hr.controller;

import com.unisedu.hr.basic.IBaseEntity;
import com.unisedu.hr.basic.IUser;
import com.unisedu.hr.entity.Employee;
import com.unisedu.hr.entity.ResponseModel;
import com.unisedu.hr.layui.Table;
import com.unisedu.hr.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Value("${web.upload}")
    private String uploadPath;

    @ModelAttribute
    public Employee initEmployee(Integer id){
        if(id!=null){
            return (Employee) employeeService.get(id);
        }else{
            return new Employee();
        }
    }

    private EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService employeeService){
        this.employeeService = employeeService;
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public IBaseEntity get(@PathVariable Integer id){
        return employeeService.get(id);
    }

    @RequestMapping(value = "info/{id}", method = RequestMethod.GET)
    public Employee getEmployeeInfo(@PathVariable Integer id){
        return employeeService.getEmployeeInfo(id);
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResponseModel addEmployee(Employee employee, ResponseModel model){
        employeeService.insert(employee);
        return model;
    }

    /**
     * 修改员工信息
     * @param employee
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseModel updateEmployee(Employee employee, ResponseModel model){
        employeeService.update(employee);
        return model;
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public Table list(Employee employee, @RequestParam Integer page, @RequestParam Integer limit){
        return employeeService.findPage(employee,page,limit);
    }

    @RequestMapping(value = "photo", method = RequestMethod.POST)
    public String  uploadPhoto(@RequestParam(name = "data") MultipartFile file, Employee employee, ResponseModel model) throws IOException {
        String fileName = "emp"+File.separator+"photo"+File.separator+new Date().getTime()+"."+file.getOriginalFilename();
        file.transferTo(new File(uploadPath+File.separator+fileName));
        employee.getEmployeeInfo().setPhoto(fileName);
        employeeService.updateEmployeePhoto(employee.getEmployeeInfo());
        return "头像上传成功";
    }
}
